package com.luban.securityjdbc.config;

import com.luban.securityjdbc.handler.MyAuthenticationFailureHandler;
import com.luban.securityjdbc.handler.MyAuthenticationSuccessHandler;
import com.luban.securityjdbc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author : fujc-dev@qq.com
 * @motto : talk is cheap, show me the code. salute the future!
 */
//@Configuration
//@EnableGlobalMethodSecurity(jsr250Enabled = true,securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig4 extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置UserDetailsService的实现类
        auth.userDetailsService(userService);

    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.formLogin() //表单提交
            .loginPage("/login.html") //自定义登录页面
            .loginProcessingUrl("/user/login")  //登录访问路径，必须和表单提交接口一样
            .successHandler(new MyAuthenticationSuccessHandler("/main.html"))
            .failureHandler(new MyAuthenticationFailureHandler("/error.html"))
            //授权
            .and().authorizeRequests()
            //设置哪些路径可以直接访问，不需要认证
            .antMatchers("/user/login","/login.html").permitAll()
            .anyRequest().authenticated()  //需要认证
            .and().csrf().disable(); //关闭csrf防护

    }

}
